package cn.zhx.xa.service.interceptor;
import cn.zhx.xa.model.vo.common.ResultCodeEnum;
import cn.zhx.xa.service.exception.BusinessException;
import cn.zhx.xa.utils.AuthContextUtil;
import cn.zhx.xa.utils.JwtUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class UserLoginAuthInterceptor implements HandlerInterceptor {

    @Resource
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        String token = request.getHeader("token");
        //解析token
        Long validUid = jwtUtils.getValidUid(token);
        if (validUid == null) {
            throw new BusinessException(ResultCodeEnum.LOGIN_AUTH);
        }
        // 将用户uid存储到ThreadLocal中
        AuthContextUtil.set(validUid);
        return true;
    }
}
